import QtQuick 2.15
import QtQuick.Controls 2.15
import "../components"
import "../Utils.js" as U

Item {
    id: pageSearchContext
    anchors.fill: parent
    property var theme: p_theme.currentTheme()
    property bool load: false
    property bool isNextPage: false
    property int selectIndex: -1
    property double fontSize: 9
    property bool isSearch: false
    property string lastSearchText: ""
    Keys.onDownPressed: {
        if (searchListProposalModel.count > selectIndex - 1) {
            selectIndex++;
        }
    }
    Keys.onUpPressed: {
        if (selectIndex >= 0) {
            selectIndex--;
        }
    }

    function onSearch(text) {
        if (text !== search.text) {
            search.text = text;
        }
        if (text.trim() === "") {
            toast.show("请输入搜索关键字");
            return;
        }
        searchListProposalModel.clear();
        selectIndex = -1;
        isSearch = true;
        load = true;
        lastSearchText = text;
        p_musicRes.getSearchList(text).then(res => {
            searchListModel.clear();
            searchListView.contentY = 0;
            searchListModel.append(res);
            searchListModel.append({
                id: -1,
                loading: true,
                text: "加载中"
            });
            load = false;
        });
    }
    function onNextPage() {
        isNextPage = true;
        p_musicRes.getSearchList(lastSearchText, 30, searchListModel.count - 1).then(res => {
            if (res.length < 30) {
                searchListModel.get(searchListModel.count - 1).loading = false;
                searchListModel.get(searchListModel.count - 1).text = "没有更多的了";
            }
            searchListModel.insert(searchListModel.count - 1, res);
            isNextPage = false;
        });
    }

    function onSearchProposal() {
        const searchText = search.text.trim();
        if (searchText === "") {
            searchListProposalModel.clear();
            selectIndex = -1;
            return;
        }
        p_musicRes.getSearchSuggest(searchText).then(res => {
            if (searchText !== search.text.trim())
                return;
            searchListProposalModel.clear();
            searchListProposalModel.append(res);
            selectIndex = -1;
            // print(JSON.stringify(res))
        });
    }
    function loadHotList() {
        p_musicRes.getSearchHot().then(res => {
            hotSearchList.clear();
            hotSearchList.append(res);
        });
    }

    Component.onCompleted: {
        loadHotList();
    }

    Rectangle {
        id: searchBox
        z: 2
        anchors.top: parent.top
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.topMargin: 20
        height: children[0].height
        width: children[0].width
        radius: 10
        clip: true
        color: theme.fontColor
        Row {
            height: 40
            Rectangle {
                height: parent.height
                width: 400
                border.color: theme.fontColor
                border.width: 2
                radius: 10
                anchors.verticalCenter: parent.verticalCenter
                clip: true
                HoverMouseArea {
                    anchors.fill: parent
                    cursorShape: Qt.IBeamCursor
                    TextInput {
                        id: search
                        anchors.fill: parent
                        verticalAlignment: TextInput.AlignVCenter
                        leftPadding: 10
                        font.pointSize: 12
                        selectByMouse: true
                        selectionColor: theme.fontColor
                        onAccepted: {
                            if (selectIndex !== -1) {
                                pageSearchContext.onSearch(searchListProposalModel.get(selectIndex).name);
                            } else {
                                pageSearchContext.onSearch(text);
                            }
                        }
                        onTextEdited: {
                            if (text !== "") {
                                pageSearchContext.onSearchProposal();
                            } else {
                                isSearch = false;
                                searchListProposalModel.clear();
                            }
                        }
                    }
                    Text {
                        visible: (search.text === "")
                        anchors.fill: parent
                        verticalAlignment: TextInput.AlignVCenter
                        leftPadding: 10
                        font.pointSize: 12
                        text: '输入你想找的音乐吧'
                        font.italic: true
                        color: "#8f" + theme.subBackgroundColor2
                    }
                }
            }
            Item {
                id: searchButton
                width: children[0].contentWidth + 40
                height: parent.height
                anchors.verticalCenter: parent.verticalCenter
                Text {
                    color: "#fff"
                    text: "搜索"
                    anchors.centerIn: parent
                    font.pointSize: 14
                    font.weight: Font.Bold
                }
                MouseArea {
                    anchors.fill: parent
                    cursorShape: Qt.PointingHandCursor
                    onClicked: {
                        pageSearchContext.onSearch(search.text);
                    }
                }
            }
        }
    }

    ListModel {
        id: searchListProposalModel
    }
    ListModel {
        id: searchListModel
        property var jsArray: convertModelToArray()
        function convertModelToArray() {
            return U.listModelToJsArray(this, ["id", "name", 'artists', 'coverImage', 'allTime', 'vip']);
        }
    }

    ListModel {
        id: hotSearchList
    }
    Column {
        z: 2
        opacity: 0.9
        anchors.horizontalCenter: parent.horizontalCenter
        width: searchBox.width
        anchors.top: searchBox.bottom
        Repeater {
            model: searchListProposalModel
            delegate: searchProposalDelegate
        }
    }
    Component {
        id: searchProposalDelegate
        Rectangle {
            id: wrapper
            color: {
                if (mouseArea.isHover || selectIndex === model.index)
                    return "#fff";
                else
                    return "#eef3ff";
            }
            width: searchBox.width
            border.width: 1
            border.color: selectIndex === model.index ? "#EEE" : "#00000000"
            height: 35
            radius: 3
            Behavior on color {
                ColorAnimation {
                    duration: 100
                }
            }
            Text {
                id: nameText
                width: parent.width * 0.6
                anchors.verticalCenter: parent.verticalCenter
                anchors.left: parent.left
                anchors.leftMargin: 10
                font.pointSize: 10
                text: name
                elide: Text.ElideRight
            }
            Text {
                id: authorText
                width: parent.width * 0.4
                anchors.verticalCenter: parent.verticalCenter
                anchors.right: parent.right
                anchors.rightMargin: 10
                font.pointSize: 9
                text: author
                color: "#999"
                font.italic: true
                elide: Text.ElideRight
                horizontalAlignment: Text.AlignRight
            }
            HoverMouseArea {
                id: mouseArea
                cursorShape: Qt.PointingHandCursor
                onClicked: {
                    pageSearchContext.onSearch(name);
                }
            }
        }
    }

    Item {
        id: hotSearchBox
        width: parent.width
        height: parent.height - searchBox.height - 40
        visible: !isSearch
        anchors.bottom: parent.bottom
        // color:"#92bd6c"
        property var positions: []
        onVisibleChanged: {
            if (visible) {
                hotSearchBoxRepeater.resetPos();
            }
        }

        Repeater {
            id: hotSearchBoxRepeater
            model: hotSearchList
            function resetPos() {
                hotSearchBox.positions = [];
                for (let i = 0; i < count; i++) {
                    itemAt(i).init();
                }
            }

            delegate: Rectangle {
                id: wrapper
                width: children[0].contentWidth + 25
                height: children[0].contentHeight + 10
                color: mouseArea.isHover ? ("#3f" + theme.subBackgroundColor2) : "#00000000"
                radius: 10
                opacity: 0
                x: Math.floor(Math.random() * (hotSearchBox.width - width))
                y: Math.floor(Math.random() * (hotSearchBox.height - height))
                scale: mouseArea.pressed ? 0.95 : 1
                Component.onCompleted: {
                    init();
                }
                function init() {
                    let tx, ty;
                    root: while (true) {
                        tx = Math.floor(Math.random() * (hotSearchBox.width - width));
                        ty = Math.floor(Math.random() * (hotSearchBox.height - height));
                        for (let pos of hotSearchBox.positions) {
                            if (Math.abs(pos.x - tx) < pos.w && Math.abs(pos.y - ty) < pos.h) {
                                continue root;
                            }
                        }
                        break;
                    }
                    x = tx;
                    y = ty;
                    hotSearchBox.positions.push({
                        x: tx,
                        y: ty,
                        w: width,
                        h: height
                    });
                    appearAnimation.running = true;
                }

                Behavior on x {
                    NumberAnimation {
                        easing.type: Easing.InOutCubic
                        duration: 1000 + Math.random() * 1000
                    }
                }
                Behavior on y {
                    NumberAnimation {
                        easing.type: Easing.InOutCubic
                        duration: 800 + Math.random() * 1000
                    }
                }

                NumberAnimation {
                    id: appearAnimation
                    running: false
                    target: wrapper
                    property: "opacity"
                    duration: 1000
                    from: 0
                    to: 1
                    easing.type: Easing.InOutQuad
                }

                Text {
                    anchors.centerIn: parent
                    text: model.text
                    color: theme.fontColor
                    font.pointSize: 10 + Math.random() * 6
                }
                Behavior on color {
                    ColorAnimation {}
                }

                HoverMouseArea {
                    id: mouseArea
                    cursorShape: Qt.PointingHandCursor
                    onClicked: {
                        pageSearchContext.onSearch(model.text);
                    }
                }
            }
        }
    }

    Row {
        id: musicRowHeader
        visible: isSearch
        height: 40
        width: parent.width - 50
        anchors.top: searchBox.bottom
        anchors.topMargin: 20
        opacity: 0.8
        Text {
            color: theme.fontColor
            font.pointSize: fontSize
            width: parent.width * 0.2 - 80
            anchors.verticalCenter: parent.verticalCenter
            horizontalAlignment: Text.AlignHCenter
            font.italic: true
            font.bold: true
            text: "#"
        }
        Text {
            color: theme.fontColor
            font.pointSize: fontSize
            width: 80
            anchors.verticalCenter: parent.verticalCenter
            horizontalAlignment: Text.AlignHCenter
            text: "封面"
        }
        Text {
            color: theme.fontColor
            font.pointSize: fontSize
            width: parent.width * 0.25
            anchors.verticalCenter: parent.verticalCenter
            horizontalAlignment: Text.AlignLeft
            elide: Text.ElideRight
            text: "歌曲名称"
        }

        Text {
            color: theme.fontColor
            font.pointSize: fontSize
            width: parent.width * 0.3
            anchors.verticalCenter: parent.verticalCenter
            horizontalAlignment: Text.AlignVCenter
            elide: Text.ElideRight
            text: "作曲家"
        }
        Text {
            color: theme.fontColor
            font.pointSize: fontSize
            width: parent.width * 0.25 - 80
            anchors.verticalCenter: parent.verticalCenter
            horizontalAlignment: Text.AlignHCenter
            elide: Text.ElideRight
            text: "时长"
        }
    }
    ListView {
        id: searchListView
        width: parent.width - 20
        height: parent.height - searchBox.height - musicRowHeader.height - 40
        visible: isSearch
        anchors.bottom: parent.bottom
        model: searchListModel
        clip: true
        ScrollBar.vertical: CScrollBar {}
        delegate: Item {
            width: searchListView.width - 30
            height: children[0].height
            MusicRow {
                visible: model.id !== -1
                parentWidth: parent.width
                playList: searchListModel.jsArray
                playInfo: U.modelToJsObj(model, ["id", "name", 'artists', 'coverImage', 'allTime', 'vip'])
                index: model.index
            }
            Component.onCompleted: {
                if (model.id !== -1) {
                    return;
                }
                const component = Qt.createComponent("../components/Loading2.qml");
                if (component.status === Component.Ready) {
                    const loading = component.createObject(this);
                    loading.text = model.text || "加载中";
                    loading.loading = model.loading;
                    if (!isNextPage && model.loading) {
                        pageSearchContext.onNextPage();
                    }
                } else if (component.status === Component.Error) {
                    console.error("加载组件时出错:", component.errorString());
                }
            }
        }
    }
}
